import datetime

import jwt

import dao
import log
import auth
from cache.local_cache import getDataFromLocalCache


def build_payload(userId, userName, expired):
    return {
        "user_id": userId,
        "username": userName,
        "exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=expired)
    }


def generate_jwt_token(userId, userName, expired):
    return jwt.encode(build_payload(userId, userName, expired),
                      auth.OAUTH_JWT_SECRET_KEY, algorithm="HS256")


def getAppAuthInfoFromDatasource(appId):
    return dao.auth_dao.getAppAuthByAppId(appId)


def verify_jwt_token(token):
    try:
        decoded = jwt.decode(token, auth.OAUTH_JWT_SECRET_KEY, algorithms=["HS256"])

        appId = decoded['user_id']
        appName = decoded['username']

        result = getDataFromLocalCache(appId, getAppAuthInfoFromDatasource)
        if not result or result['app_name'] != appName:
            return 4

        return 0
    except jwt.ExpiredSignatureError as e:
        log.logger.error(e.__str__())
        return 1
    except jwt.InvalidTokenError as e:
        log.logger.error(e.__str__())
        return 2
    except Exception as e:
        log.logger.error(e.__str__())
        return 3

